﻿using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.Collections.Extensions;
using Abp.Extensions;
using Abp.Linq.Extensions;
using System.Collections.Generic;
using System.Linq;
using Partner.Surround.Authorization.Permissions.Dto;

namespace Partner.Surround.Authorization.Permissions
{
    /// <summary>
    /// 权限应用层服务
    /// </summary>
    public class PermissionAppService : SurroundAppServiceBase, IPermissionAppService
    {
        public ListResultDto<FlatPermissionWithLevelDto> GetAllPermission()
        {
            var permissions = PermissionManager.GetAllPermissions();
            var rootPermissions = permissions.Where(p => p.Parent == null);

            var result = new List<FlatPermissionWithLevelDto>();

            foreach (var rootPermission in rootPermissions)
            {
                var level = 0;
                AddPermission(rootPermission, permissions, result, level);
            }

            return new ListResultDto<FlatPermissionWithLevelDto>
            {
                Items = result
            };
        }

        public ListResultDto<TreePermissionDto> GetAllPermissionTree()
        {
            var rootPermissions = PermissionManager
                .GetAllPermissions()
                .Where(p => p.Parent == null);

            var tmp = ObjectMapper.Map<List<TreePermissionDto>>(rootPermissions);

            return new ListResultDto<TreePermissionDto>(tmp);
        }

        public PagedResultDto<PermissionDto> GetPagedPermission(GetPagedPermissionInput input)
        {
            //查询所有权限
            var query = PermissionManager.GetAllPermissions().WhereIf(!input.PermissionName.IsNullOrWhiteSpace(), p => p.Name.Contains(input.PermissionName));

            var totalCount = query.Count();

            var items = query.Skip(input.SkipCount).Take(input.MaxResultCount).ToList();

            return new PagedResultDto<PermissionDto>(
                totalCount,
                items.Select(item =>
                {
                    return ObjectMapper.Map<PermissionDto>(item);
                }).ToList());
        }

        private void AddPermission(Permission permission, IReadOnlyList<Permission> allPermissions, List<FlatPermissionWithLevelDto> result, int level)
        {
            var flatPermission = ObjectMapper.Map<FlatPermissionWithLevelDto>(permission);
            flatPermission.Level = level;
            result.Add(flatPermission);

            if (permission.Children == null) return;

            var children = allPermissions.Where(p => p.Parent != null && p.Parent.Name == permission.Name).ToList();

            foreach (var childPermission in children) AddPermission(childPermission, allPermissions, result, level + 1);
        }
    }
}
